package com.kcs.fxmargin.service;

import java.sql.Connection;
import java.util.List;

import com.kcs.common.utils.ConnectionUtils;
import com.kcs.common.utils.Constant;
import com.kcs.common.utils.OIDGenerator;
import com.kcs.fxmargin.bo.SetupRoleProfileBO;
import com.kcs.fxmargin.dao.SetupRoleProfileDAO;
import com.kcs.fxmargin.model.MRole;
import com.kcs.fxmargin.model.MUsersAuth;

public class SetupRoleProfileService {

	public SetupRoleProfileBO getFunctionList(SetupRoleProfileBO bo)throws Exception{
		Connection conn = null;
		SetupRoleProfileDAO dao = null;
		SetupRoleProfileBO srp = null;
		List<MRole> roleList = null;
		MRole mr = null;
		MUsersAuth mua = null;
		String id = null;
		int flag = 0;
		String activeStatus = "A";
		int countInsert = 0;
		
		try{
			
			conn = ConnectionUtils.getConnection(Constant.MSSQL, Constant.TO);
			dao = new SetupRoleProfileDAO();
			bo = dao.getFunctionList(bo, conn);
			
			if(bo.getFunctionList() != null){
				for(int i=0; i<bo.getFunctionList().size(); i++){
					srp = bo.getFunctionList().get(i);
					
					if(srp.getAuthId() == null){
						
						//-- Get Role List
						if(roleList == null){
							bo = dao.getRoleList(bo, conn);
							roleList = bo.getRoleList();
						}
						
						//-- Generate MUsersAuth
						for(int j=0; j<roleList.size(); j++){
							mr = roleList.get(j);
							
							id = OIDGenerator.create();
							
							mua = new MUsersAuth();
							mua.setId(id);
							mua.setMenuId(srp.getMenuId());
							mua.setRoleId(mr.getId());
							mua.setFlag(flag);
							mua.setActiveStatus(activeStatus);
							dao.insertMUsersAuth(mua, conn);
						
							countInsert++;
						}
					}
				}
				
				if(countInsert > 0){
					conn.commit();
					bo = dao.getFunctionList(bo, conn);
				}	
				
			}
			
		}catch(Exception e){
			throw e;
		}finally{
			if(conn != null){
				try{
					conn.close();
				}catch(Exception ex){
					throw ex;
				}
			}
		}
		
		return bo;
		
	}
	
	public void updateRoleProfile(SetupRoleProfileBO bo)throws Exception{
		Connection conn = null;
		SetupRoleProfileDAO dao = null;
		
		try{
			
			conn = ConnectionUtils.getConnection(Constant.MSSQL, Constant.TO);
			dao = new SetupRoleProfileDAO();
			dao.updateRoleProfile(bo, conn);
			conn.commit();
			
		}catch(Exception e){
			throw e;
		}finally{
			if(conn != null){
				try{
					conn.close();
				}catch(Exception ex){
					throw ex;
				}
			}
		}
	}
}
